#-*-coding:utf-8-*-
# Create your views here.
from models import Members
from models import Salesperson
from crm.models import Salesperson_groups   #编辑添加分组   huangzy edit
from models import Agent
from models import Projects
from models import Project_sales_rate, Project_allocate
from crm.models import Sales_record
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect

import datetime

"""调用分配客户显示页"""

def show (request, s_id = ""):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    """获取所有项目数"""
    pj = Projects.objects.order_by('id')
    sp = Salesperson.objects.order_by('id')
    sg = Salesperson_groups.objects.order_by('id') #获取用户组数据 huangzy edit
    sg = Salesperson_groups.objects.filter(status=1) #获取用户组数据 huangzy edit
    """获取所有代理数"""
    agent = Agent.objects.order_by('id')
    if s_id:
        s_id = int(s_id)
    return render_to_response('allocation.html', {'pj':pj, 'sp':sp,'sg':sg, 'agent':agent, 's_id':s_id})   #获取用户组数据 huangzy edit


"""开始分配"""
def allocation_do (request):
    #import datetime
    """项目与代理ID,客户ID段.如果没选择则为0"""
    new_data = request.POST.copy()
    projects_id = request.POST.get('projects_id', '0')
    agent_id = request.POST.get('agent_id', '0')
    group_id = request.POST.get('group','0')   #获取用户组数据 huangzy edit
    startid = request.POST.get('startid', '0')
    endid = request.POST.get('endid', '0')
    isblack = request.POST.get('isblack', '0')
    dagain = request.POST.get('dagain', '0')
    sid_list = new_data.getlist('sids')#选中了哪个Sales的客户要被分配
    interlevel = request.POST.get('interlevel', '')
    start_date = request.GET.get('start_date', 'begin')
    end_date = request.GET.get('end_date', 'now')

    temp_list = []
    for i, pid in enumerate(sid_list):
        temp_list.append(pid)
    
    """是否删除SALES前把将要删除的SALES的客户分给其它人"""
    s_id = request.POST.get('s_id', '0')
    if s_id == '':
        s_id = '0'
    """查找所有SALES列表"""
    allsp = Salesperson.objects.order_by('id')
    """遍历一次SALES与传过来的SALES比较.得到选择分配给多少个SALES"""
    """变量forallsales用来记录一共选了多少个sales"""
    forallsales = 0
    listsales = []
    #用于记录分给哪些选择的sales
    #用于记录剩下未分配的SALES列表
    lastsales = []

    for allsp in allsp:
        postps = 'sp[' + str(allsp.id) + ']'
        postps = request.POST.get(postps, '0')
        if postps == '1':
            forallsales = forallsales + 1
            listsales.append(allsp.id)
            lastsales.append(allsp.id)
    """如果一个sales都不选则不用分配,并具返回错误提示要求最少选择一个sales"""
    if (forallsales < 1) and (s_id == '0'):
        pj = Projects.objects.order_by('id')
        sp = Salesperson.objects.order_by('id')
        agent = Agent.objects.order_by('id')
        if s_id:
            s_id = int(s_id)
        return render_to_response('allocation.html', {'pj':pj, 'sp':sp, 's_id':s_id, 'agent':agent, 'errormsg':'you have to choose a sales at least'})
    #没选SALES,但是删除SALES操作,可以不选,分配给空SALES
    if (forallsales < 1) and (s_id != '0'):
        listsales = [0]
    """开始平均分配
           首先按要求查出所有尚未有sales跟进的customers"""

    """管理员选了按项目分配,只查选中项目的相关客户"""
    if projects_id != '0':
        customers = Members.objects.filter(projects__id = projects_id)
    else:
        if s_id == '0':
            customers = Members.objects.all()
        else:
            customers = Members.objects.filter(salesperson__id = s_id)

    """选择把某些Sales的客户分配出去."""
    if temp_list:
        customers = customers.filter(salesperson__id__in = temp_list)
    """选择把某些Sales的客户中状态为什么的分配出去."""
    if interlevel != '':
        customers = customers.filter(interlevel = interlevel)

    """按注册日期筛选"""
    if start_date == 'begin' and end_date != 'now':
        customers = customers.filter(regtime__lte = end_date)
    elif start_date != 'begin' and end_date == 'now':
        customers = customers.filter(regtime__gte = start_date)
    elif start_date != 'begin' and end_date != 'now':
        customers = customers.filter(regtime__range = (start_date, end_date))


    """如果选择是人代理,则只查属于被选代理的客户"""
    if agent_id != '0':
        customers = customers.filter(agent__id = agent_id)
    #allcustomer2=int(customers.count())
    """如果填写了客户ID段,则只分配此ID段的用户"""
    if startid != '0':
        customers = customers.filter(id__gte = startid, id__lte = endid)

    """是否重新分配,重新分配意思是在上面已有条件下将原已分配的重新分配"""

    if dagain == '0' and s_id == '0':
        customers = customers.filter(salesperson__id = 0)

    #如果选择只分配已变为黑色的用户
    last_allocate_value = datetime.datetime.now()
    if isblack != '0':
        #import datetime
        from django.db.models import Q
        nowtime = datetime.datetime.now()
        t1 = nowtime - datetime.timedelta(days = 60)
        t2 = nowtime - datetime.timedelta(days = 120)
        customers = customers.filter(Q(last_contact__lte = t1), Q(interlevel = '0') | Q(interlevel = '3') | Q(interlevel = '4') | Q(last_contact__lte = t2))
        last_allocate_value = datetime.datetime.now()
    """customers为最终找出要分配的客户列表"""
    customers = customers.order_by('-id')

    """开始循环分配查出来的客户"""
    """客户总数"""
    allcustomer = int(customers.count())

    """如果有填分配百度比"""
    """forrate用于记录是否有输入百分比"""
    forrate = 0
    """ratelist[]表列用于记录各自占的百分比"""
    ratelist = []
    for rat in listsales:
        sprate = 'sprate[' + str(rat) + ']'
        sprate = request.POST.get(sprate, '0')
        """将对应的百分比写入列表"""
        ratelist.append(sprate)
        """如果有百分比不为0."""
        if sprate != '0' and sprate != '':
            #记录输入的百分比个数
            forrate = forrate + 1
            #检查输入类型
            try:
                sprate = str(sprate)
                sprate = float(sprate)
            except:
                pj = Projects.objects.order_by('id')
                sp = Salesperson.objects.order_by('id')
                agent = Agent.objects.order_by('id')
                if s_id:
                    s_id = int(s_id)
                return render_to_response('allocation.html', {'pj':pj, 'sp':sp, 's_id':s_id, 'agent':agent, 'errormsg2':'The type of Percentage must be a number and you can choose doesn\'t enter the Percentage then it will be allocated by average'})
        """
        if sprate!='0' and sprate!='':
            sprate=str(sprate)
            sprate=float(sprate)
            allnum=31.0*sprate
            sprate=allnum/100.0
            sprate=ratelist[0]
        """

    startc = 0
    nownum = 0

    #nownum用于记录此次循环分到第几个人,nownum<=forallsales,以此循环以达到平均分配
    #如果没输入按多少百分比来分配则实行平均分配
    #import datetime
    today = datetime.date.today()
    today = str(today)
    if forrate == 0:
        for customer in customers:
            if nownum >= forallsales:
                nownum = 0
            member = Members.objects.get(pk = customer.id)
            #2008-09-23当改变sales时需记录
            if member.salesperson_id != listsales[nownum]:
                sr_list = Sales_record.objects.filter(members = member).order_by('-id')[:1]
                if sr_list:
                    #原已有记录直接入库就可以
                    lastid = ''
                    for sr in sr_list:
                        lastid = sr.id
                    if lastid:
                        try:
                            last_record_obj = Sales_record.objects.get(pk = lastid)
                        except:
                            last_record_obj = ''
                        try:
                            last_record_obj.endtime = today
                            last_record_obj.save()
                        except:
                            pass
                    try:
                        sales_obj = Salesperson.objects.get(pk = listsales[nownum])
                        srinfo2 = Sales_record(
                        members = member,
                        salesperson = sales_obj,
                        starttime = today,
                        endtime = '',
                        )
                        srinfo2.save()
                    except:
                        pass
                else:
                    #新的记录
                    had_sales_id = 0
                    try:
                        had_sales_id = int(member.salesperson_id)
                    except:
                        pass
                    if had_sales_id != 0:
                        try:
                            sales_obj = Salesperson.objects.get(pk = had_sales_id)
                            srinfo = Sales_record(
                            members = member,
                            salesperson = sales_obj,
                            starttime = str(member.regtime)[:10],
                            endtime = today,
                            )
                            srinfo.save()
                        except:
                            pass
                        try:
                            sales_obj2 = Salesperson.objects.get(pk = listsales[nownum])
                            srinfo2 = Sales_record(
                            members = member,
                            salesperson = sales_obj2,
                            starttime = today,
                            endtime = '',
                            )
                            srinfo2.save()
                        except:
                            pass
                    else:
                        try:
                            sales_obj2 = Salesperson.objects.get(pk = listsales[nownum])
                            srinfo2 = Sales_record(
                            members = member,
                            salesperson = sales_obj2,
                            starttime = today,
                            endtime = '',
                            )
                            srinfo2.save()
                        except:
                            pass
            #end 2008-09-23当改变sales时需记录
            member.salesperson_id = listsales[nownum]
            nownum = nownum + 1
            member.last_allocate = last_allocate_value
            member.men_area = group_id
            if isblack != '0':
                member.status = '0'
                member.interlevel = '0'
            member.save()
        forallsales = 0
            #pass
            #return render_to_response('crm/test.html',{'customers':customers})
    else:
        #按百分比分配 allcustomer 客户总数
        nownum2 = 0
        salesnum = 0
        tempnum = 0
        for1num = 0
        """ratelist对应的SALES的百分比"""
        for ratelist in ratelist:
            if ratelist != '' and ratelist != '0':
                myallcustomer = allcustomer * int(ratelist) / 100
                myallcustomer = tempnum + myallcustomer
                for2 = 0
                for customer in customers:
                    if for2 >= tempnum and tempnum < myallcustomer:
                        member = Members.objects.get(pk = customer.id)
                        #2008-09-23当改变sales时需记录
                        if member.salesperson_id != lastsales[salesnum]:
                            sr_list = Sales_record.objects.filter(members = member).order_by('-id')[:1]
                            if sr_list:
                                #原已有记录直接入库就可以
                                lastid = ''
                                for sr in sr_list:
                                    lastid = sr.id
                                if lastid:
                                    try:
                                        last_record_obj = Sales_record.objects.get(pk = lastid)
                                    except:
                                        last_record_obj = ''
                                    try:
                                        last_record_obj.endtime = today
                                        last_record_obj.save()
                                    except:
                                        pass
                                try:
                                    sales_obj = Salesperson.objects.get(pk = lastsales[salesnum])
                                    srinfo2 = Sales_record(
                                    members = member,
                                    salesperson = sales_obj,
                                    starttime = today,
                                    endtime = '',
                                    )
                                    srinfo2.save()
                                except:
                                    pass
                            else:
                                #新的记录
                                had_sales_id = 0
                                try:
                                    had_sales_id = int(member.salesperson_id)
                                except:
                                    pass
                                if had_sales_id != 0:
                                    try:
                                        sales_obj = Salesperson.objects.get(pk = had_sales_id)
                                        srinfo = Sales_record(
                                        members = member,
                                        salesperson = sales_obj,
                                        starttime = str(member.regtime)[:10],
                                        endtime = today,
                                        )
                                        srinfo.save()
                                    except:
                                        pass
                                    try:
                                        sales_obj2 = Salesperson.objects.get(pk = lastsales[salesnum])
                                        srinfo2 = Sales_record(
                                        members = member,
                                        salesperson = sales_obj2,
                                        starttime = today,
                                        endtime = '',
                                        )
                                        srinfo2.save()
                                    except:
                                        pass
                                else:
                                    try:
                                        sales_obj2 = Salesperson.objects.get(pk = lastsales[salesnum])
                                        srinfo2 = Sales_record(
                                        members = member,
                                        salesperson = sales_obj2,
                                        starttime = today,
                                        endtime = '',
                                        )
                                        srinfo2.save()
                                    except:
                                        pass
                        #end 2008-09-23当改变sales时需记录
                        member.salesperson_id = lastsales[salesnum]
                        tempnum = tempnum + 1
                        for2 = for2 + 1
                        member.last_allocate = last_allocate_value
                        member.men_area = group_id
                        if isblack != '0':
                            member.status = '0'
                            member.interlevel = '0'
                        member.save()
                        #if tempnum>myallcustomer:
                            #break
                    else:
                        #break
                        #tempnum=tempnum+1
                        for2 = for2 + 1
                forallsales = forallsales - 1
                temp = int(lastsales[salesnum])
                listsales.remove(temp)
            salesnum = salesnum + 1


    #没完全填写百分比,将剩下的按平均分配
    if forallsales > 0:
        nownum3 = 0
        temp3 = 0
        for customer in customers:
            if nownum3 >= forallsales:
                nownum3 = 0
            if temp3 >= tempnum:
                member = Members.objects.get(pk = customer.id)
                #2008-09-23当改变sales时需记录
                if member.salesperson_id != listsales[nownum3]:
                    sr_list = Sales_record.objects.filter(members = member).order_by('-id')[:1]
                    if sr_list:
                        #原已有记录直接入库就可以
                        lastid = ''
                        for sr in sr_list:
                            lastid = sr.id
                        if lastid:
                            try:
                                last_record_obj = Sales_record.objects.get(pk = lastid)
                            except:
                                last_record_obj = ''
                            try:
                                last_record_obj.endtime = today
                                last_record_obj.save()
                            except:
                                pass
                        try:
                            sales_obj = Salesperson.objects.get(pk = listsales[nownum3])
                            srinfo2 = Sales_record(
                            members = member,
                            salesperson = sales_obj,
                            starttime = today,
                            endtime = '',
                            )
                            srinfo2.save()
                        except:
                            pass
                    else:
                        #新的记录
                        had_sales_id = 0
                        try:
                            had_sales_id = int(member.salesperson_id)
                        except:
                            pass
                        if had_sales_id != 0:
                            try:
                                sales_obj = Salesperson.objects.get(pk = had_sales_id)
                                srinfo = Sales_record(
                                members = member,
                                salesperson = sales_obj,
                                starttime = str(member.regtime)[:10],
                                endtime = today,
                                )
                                srinfo.save()
                            except:
                                pass
                            try:
                                sales_obj2 = Salesperson.objects.get(pk = listsales[nownum3])
                                srinfo2 = Sales_record(
                                members = member,
                                salesperson = sales_obj2,
                                starttime = today,
                                endtime = '',
                                )
                                srinfo2.save()
                            except:
                                pass
                        else:
                            try:
                                sales_obj2 = Salesperson.objects.get(pk = listsales[nownum3])
                                srinfo2 = Sales_record(
                                members = member,
                                salesperson = sales_obj2,
                                starttime = today,
                                endtime = '',
                                )
                                srinfo2.save()
                            except:
                                pass
                #end 2008-09-23当改变sales时需记录
                member.salesperson_id = listsales[nownum3]
                nownum3 = nownum3 + 1
                member.last_allocate = last_allocate_value
                member.men_area = group_id
                if isblack != '0':
                    member.status = '0'
                    member.interlevel = '0'
                member.save()
            temp3 = temp3 + 1
    """如果是删SALES前的分配把SALES删掉"""
    if s_id != '0':
        Salesperson.objects.filter(pk = s_id).delete()

    return HttpResponse("Completed distribution,<br /><br /><a href=\"/ulist\">Click here to View the result</a>")
    #return render_to_response('tt.html',{'allcustomers':allcustomer,'sprate':tempnum})



    #分配设定.
def allocation_set (request):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    pth = pw = pten = psixteen = ''
    """获取所有项目数"""
    sp = Salesperson.objects.order_by('id')
    sg = Salesperson_groups.objects.order_by('id') #获取用户组数据 huangzy edit
    sg = Salesperson_groups.objects.filter(status=1) #获取用户组数据 huangzy edit
    uncclist = Project_sales_rate.objects.filter(project_id = 4)
    harvardlist = Project_sales_rate.objects.filter(project_id = 10)
    stanfordlist = Project_sales_rate.objects.filter(project_id = 3)
    iowambalist = Project_sales_rate.objects.filter(project_id = 16)
    bs_list = Project_sales_rate.objects.filter(project_id = 18)
    smp_list = Project_sales_rate.objects.filter(project_id = 17)
    return render_to_response('allocation_set.html', {'sp':sp,'sg':sg, 'uncclist':uncclist, 'harvardlist':harvardlist, 'stanfordlist':stanfordlist, 'iowambalist':iowambalist, 'onproject_id':'0',
    'pth':pth, 'pw':pw, 'pten':pten, 'psixteen':psixteen, 'bs_list':bs_list, 'smp_list':smp_list})


    #处理分配.
def allocation_set_in (request):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')

    project_id = request.POST.get('project_id', '0')

    """查找所有SALES列表"""
    allsp = Salesperson.objects.filter(level = 'sales')
    allrate = 0
    group_id = request.POST.get('group_id')
#    return HttpResponse()
    for sale in allsp:
        if str(sale.group) == group_id:
            postps = 'sp['+str(sale.group)+'][' + str(sale.id) + ']'
            sprate = request.POST.get(postps, '0')
            if sprate == '':
                sprate = 0
            allrate += float(sprate)
    
    if int(allrate) != 100:
        return HttpResponse("<font colur='red'>error, all the rate should be 100</font><br /><br /><input type='button' class='button' name='back'  id='reset' value=' Back ' onclick='javascrip:history.back(1)' />")

    #已存在的更新,否则插入.
    for sale in allsp:
        if str(sale.group) == group_id:
            postps = 'sp['+str(sale.group)+'][' + str(sale.id) + ']'
            sprate = request.POST.get(postps, '0')
            try:
                psr = Project_sales_rate.objects.get(project_id = project_id, salesperson_id = sale.id)
                psr.rate = sprate
                psr.group_id = group_id
            except:
                psr = Project_sales_rate(
                rate = sprate,
                project_id = project_id,
                salesperson_id = sale.id,
                group_id = group_id,
                )
                #对应插入Project_allocate表
                pa = Project_allocate(
                sum = 0,
                project_id = project_id,
                salesperson_id = sale.id,
                group_id = group_id,
                )
                pa.save()
            psr.save()

    """获取所有项目数"""
    sp = Salesperson.objects.order_by('id')
    sg = Salesperson_groups.objects.order_by('id') #获取用户组数据 huangzy edit

    uncclist = Project_sales_rate.objects.filter(project_id = 4)
    harvardlist = Project_sales_rate.objects.filter(project_id = 10)
    stanfordlist = Project_sales_rate.objects.filter(project_id = 3)
    iowambalist = Project_sales_rate.objects.filter(project_id = 16)
    bs_list = Project_sales_rate.objects.filter(project_id = 18)
    smp_list = Project_sales_rate.objects.filter(project_id = 17)
    errorinfo = 'ok'
    return render_to_response('allocation_set.html', {'sp':sp,'sg':sg,'defgroup':int(group_id), 'uncclist':uncclist, 'harvardlist':harvardlist, 'stanfordlist':stanfordlist, 'iowambalist':iowambalist, 'errorinfo':errorinfo, 'onproject_id':project_id, 'bs_list':bs_list,'smp_list':smp_list})



    #清空已分配记录,重新分配.
def clear_caterecord (request, pj_id = ''):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    """获取所有项目数"""
    pa_list = Project_allocate.objects.filter(project_id = pj_id)
    for pa in pa_list:
        pa.sum = 0
        pa.save()
    pth = pw = pten = psixteen = ''
    if pj_id == 4 or pj_id == '4':
        pth = 'ok'
    if pj_id == 3 or pj_id == '3':
        pw = 'ok'
    if pj_id == 10 or pj_id == '10':
        pten = 'ok'
    if pj_id == 16 or pj_id == '16':
        psixteen = 'ok'

    """获取所有项目数"""
    sp = Salesperson.objects.order_by('id')
    sg = Salesperson_groups.objects.order_by('id') #获取用户组数据 huangzy edit

    uncclist = Project_sales_rate.objects.filter(project_id = 4)
    harvardlist = Project_sales_rate.objects.filter(project_id = 10)
    stanfordlist = Project_sales_rate.objects.filter(project_id = 3)
    iowambalist = Project_sales_rate.objects.filter(project_id = 16)
    return render_to_response('allocation_set.html', {'sp':sp,'sg':sg, 'uncclist':uncclist, 'harvardlist':harvardlist, 'stanfordlist':stanfordlist, 'iowambalist':iowambalist, 'onproject_id':'0',
    'pth':pth, 'pw':pw, 'pten':pten, 'psixteen':psixteen})

